<template>
  <!-- 聊天界面 -->
  <div class="box">
    <!--顶部聊天头-->
    <div class="header clearfix">
      <h2 class="name">meowcook</h2>
      <div class="button"><!-- 删除操作三个按钮 -->
        <el-button @click="getMsgIdList" v-show="!showBox" class="deleteBut" type="primary">确认删除</el-button>
        <el-button @click="clickShowBox" v-show="!showBox" class="deleteBut" type="primary">取消</el-button>
        <el-button @click="clickShowBox" v-show="showBox" class="deleteBut" type="primary">删除消息</el-button>
      </div>
      <!-- <img src="./img/head.png" alt=""> -->
    </div>
    <!--聊天框-->
    <div class="chatarea" ref="chat">
      <ul class="talk_list">
        <li v-for="m in wsStore.MessageList[sessionId]" :class="m.speaker.id==Number(userId)?'right_word':'left_word'">
          <el-checkbox @click="getDelId(m.id)" v-show="!showBox" class="delBox" v-model="wsStore.checkDelId[m.id]"  size="large" />
          <img src="" alt="">
          <span>{{ m.content }}</span>
        </li>
      </ul>
    </div>
    <!--输入框-->
    <div class="enter">
      <img src="" alt="">
      <!-- <input type="inputarea" class="enterarea" placeholder="请输入信息" v-model.trim="pMessage"> -->
       <textarea ref="input" v-model="pMessage" autocomplete="off" class="enterarea" placeholder="请输入信息" rows="4"></textarea>
      <!-- <button >发送</button> -->
      <el-button class="enterbtn" type="primary" @click="deliver">发送</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useWebSocketStore } from '@/stores/websocket'
import axios, { all } from 'axios'
import { reactive, ref, nextTick, onBeforeUnmount, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
//几乎每个组件都要获取以便后续使用
let userId = sessionStorage.getItem('userId')
let route = useRoute()//用于从路由中的params或query中获取值
const router = useRouter()
const wsStore = useWebSocketStore()


// 使用响应式变量存储sessionId
let sessionId = ref(0)
// 删除按钮的展示隐藏
let showBox = ref(true)
// 确认发送的聊天文字消息
let pMessage = ref('')

// 聊天框对象用于bom操作
const chat = ref<HTMLElement | null>(null)




// ChatPage.vue展示时默认调用onMounted并执行一次updateSessionId()，设置一个路由监听
// 用户在切换聊天对象，ChatPage.vue并没有因此卸载，通过路由监听执行updateSessionId()  
// 当用户离开路由chatpage,ChatPage.vue组件卸载，执行卸载监听

// 清理函数引用
let cleanupAfterEach: (() => void) | null = null
// 在组件挂载时设置路由监听
onMounted(() => {
  updateSessionId()//获取的不只是sessionId
  
  // 只在组件挂载时设置一次路由监听
  cleanupAfterEach = router.afterEach(async(to, from) => {
    // 只有当导航到chatpage时才更新sessionId
    if (to.name === 'chatpage') {
      await updateSessionId()  
    }
  })
})

// 组件卸载时清理路由监听
onBeforeUnmount(() => {
  if (cleanupAfterEach) {
    cleanupAfterEach()
    cleanupAfterEach = null
  }
})


// 监听WebSocket消息列表变化，自动滚动到底部
watch(
  () => wsStore.MessageList[sessionId.value],
  () => {
    nextTick(() => {
      if (chat.value) {
        chat.value.scrollTo({
          top: chat.value.scrollHeight,
          behavior: 'smooth'
        })
      }
    })
  },
  { deep: true }
)

// 在离开聊天页面路由之前将当前会话未读消息置为零
// router.beforeEach(async(to, from)=>{
//   // 只有当从chatpage路由离开时才重置未读计数
//   if (from.name === 'chatpage' && to.name !== 'chatpage') {
//     // 调用接口设置未读消息数为0
//     await axios({
//       url:'/api/message/setUncheckNumZero',
//       method:'post',
//       params: {
//         sessionId: sessionId.value
//       }
//     })
//     // wsStore.unreadCountMap[sessionId.value] = 0
//   }
// })


// 用于记录聊天过后最新的messageIdList，以便后续展示最新的聊天记录
let messageIdList = reactive<number[]>([])


// 更新sessionId的函数，不只是更新sessionId
async function updateSessionId() {
  const currentSessionId = route.query.sessionId//获取当前路由传来的sessionID
  const currentMessageIdList = route.query.messageIdList//获取当前路由传来的messageIdList列表

  // 如果有传来sessionId
  if (currentSessionId) {
    sessionId.value = Number(currentSessionId)//保留当前sessionid
    // 正确更新响应式数组,先置为空
    messageIdList.length = 0
    if (Array.isArray(currentMessageIdList)) {//如果有则将当前id列表值赋值给messageIdList
      currentMessageIdList.forEach(id => messageIdList.push(Number(id)))
    } else if (currentMessageIdList) {
      messageIdList.push(Number(currentMessageIdList))
    }
    console.log('当前sessionId:', sessionId.value)
    console.log('当前messageIdList:', Object.values(messageIdList))


    // // 调用接口设置未读消息数为0
    // await axios({
    //   url:'/api/message/setUncheckNumZero',
    //   method:'post',
    //   params: {
    //     sessionId: sessionId.value
    //   }
    // })
    

    // 获取最消息列表
    const messageListAxios = await axios({
      url:'/api/message/getMessageList',
      method:'post',
      data: messageIdList,
      headers:{'Content-Type':'application/json'}
    })
    // 清空并重新设置wsStore里维护的消息列表，确保响应式更新
    // 确保MessageList[sessionId.value]存在，如果不存在则初始化为空数组
    if (!wsStore.MessageList[sessionId.value]) {
      wsStore.MessageList[sessionId.value] = []
    } else {
      wsStore.MessageList[sessionId.value].splice(0)
    }
    messageListAxios.data.data.forEach((msg: any) => {//更新赋值
      wsStore.MessageList[sessionId.value].push({ ...msg })
    })
    console.log('消息列表'+JSON.stringify(wsStore.MessageList[sessionId.value]));
    

    // 其实就是切换聊天界面会将已选择删除的消息勾勾给清除掉，全部赋值为false
    wsStore.clearCheckDelId()
    wsStore.MessageList[sessionId.value].forEach(m =>{
      wsStore.checkDelId[m.id] = false
    })


    // 更新会话列表，更新新的消息列表id
    const sessionListAxios = await axios({
      url:'/api/session/getSessionList',
    })
    // 清空并重新设置会话列表，确保响应式更新
    wsStore.sessionList.length = 0
    sessionListAxios.data.data.forEach((session: any) => {
      wsStore.sessionList.push({ ...session })
    })


    // 滚动到底部
    nextTick(() => {
      if (chat.value) {
        chat.value.scrollTo({
          top: chat.value.scrollHeight,
          behavior: 'smooth'
        })
      }
    })
  }
  

}



interface MessageDTO{
  speakerId:number
  nickname:string
  avatarUrl:string
  sessionId:number
  content:string
}
let message:MessageDTO = {
  speakerId:0,
  nickname:'',
  avatarUrl:'',
  sessionId:0,
  content:''
}  


async function deliver() {
  if (pMessage.value.trim() === '') {
    return
  }
  
  // 创建消息对象
  message = {
    speakerId: Number(userId),
    nickname: userMessage.nickname,
    avatarUrl: userMessage.avatarUrl,
    sessionId: Number(sessionId.value),
    content: pMessage.value
  }
  
  console.log('发送消息时的sessionId:', sessionId.value)
  
  // 发送消息到WebSocket
  wsStore.sendMessage(message)
  // allMess.push(wsStore.lastMessage)
  // Object.assign(wsStore.wsMessageList,allMess)

  // 清空输入框
  pMessage.value = ''

  console.log('messageIdList:', Object.values(messageIdList))
  

  // 刷新会话列表，更新新的消息列表id
  const sessionListAxios = await axios({
    url:'/api/session/getSessionList',
  })
  // 清空并重新设置会话列表，确保响应式更新
  wsStore.sessionList.length = 0
  sessionListAxios.data.data.forEach((session: any) => {
    wsStore.sessionList.push({ ...session })
  })
}





//以后可能会用到ai聊天

  // axios({
  //   url: 'https://hmajax.itheima.net/api/robot',
  //   params: {
  //     spoken: pMessObj.message
  //   }
  // }).then(res => {
  //   aiMessage.value = res.data.data.info.text//获取人机回复语句
  //   let aiMessObj = { message: aiMessage.value, class: 'left_word' }//创建并加入数组
  //   // allMess.push(aiMessObj)
  //   nextTick(() => {
  //     if (chat.value) {
  //       chat.value.scrollTo({
  //         top: chat.value.scrollHeight,
  //         behavior: 'smooth'
  //       })
  //     }
  //   })
  // })


function getDelId(messageId:number){
  console.log(messageId);
}

// 获取选中删除的消息id列表
async function getMsgIdList(){
  console.log(wsStore.checkDelId);
  
  // 根据checkDelId中标记为false的ID获取要保留的消息ID数组，用于传输给后端
  const idsToKeep = Object.keys(wsStore.checkDelId)
    .filter(key => wsStore.checkDelId[Number(key)] === false)
    .map(key => Number(key))
  console.log('要保留的消息ID:', idsToKeep);

  // 删除消息接口，返回最新的删除过后的信息id列表
  const deleteResponse = await axios({
    url:'/api/message/deleteMessage',
    method:'post',
    params:{
      sessionId:sessionId.value
    },
    data:idsToKeep,
    headers:{'Content-Type':'application/json'}
  })
  console.log('删除API响应:', deleteResponse.data);

  // 如果将要删除的消息大于0条
  if (idsToKeep.length > 0) {
    // 过滤得到没有被删除的消息列表
    const filteredMessages = wsStore.MessageList[sessionId.value].filter(message => 
      wsStore.checkDelId[message.id] === false
    )

    // 将wsStore维护的wsMessageList置为空并重新附上删除后的值
    // 确保MessageList[sessionId.value]存在，如果不存在则初始化为空数组
    if (!wsStore.MessageList[sessionId.value]) {
      wsStore.MessageList[sessionId.value] = []
    } else {
      wsStore.MessageList[sessionId.value].splice(0)
    }
    filteredMessages.forEach(msg => wsStore.MessageList[sessionId.value].push(msg))

    
    // 只删除被删除消息对应的checkDelId数据
    Object.keys(wsStore.checkDelId).forEach(key => {
      if (wsStore.checkDelId[Number(key)] === true) {
        delete wsStore.checkDelId[Number(key)]
      }
    })
    
    // 移除已删除的消息ID
    const deletedIds = Object.keys(wsStore.checkDelId)
      .filter(key => wsStore.checkDelId[Number(key)] === undefined)
      .map(key => Number(key))
    
    // messageIdList置为空，并重新赋值
    messageIdList.length = 0
    wsStore.MessageList[sessionId.value].forEach(message => {
      messageIdList.push(message.id)
    })
    
    console.log('删除后的消息列表:', wsStore.wsMessageList);
    console.log('更新后的messageIdList:', Object.values(messageIdList));
    showBox.value = !showBox.value
  } else {
    alert('确定全部删除吗')
    console.log('没有选择要保留的消息');
  }
}

// 三个删除按钮显示隐藏
function clickShowBox(){
  showBox.value = !showBox.value
}




// 用户信息接口
interface userMe {
  id: number
  nickname: string
  avatarUrl: string
  isAdmin: number
}
let userMessage: userMe = {//为用户部分信息对象设置默认值
  id: 0,
  nickname: '加载中',
  avatarUrl: '',
  isAdmin: 0
}
// axios获取后端传来的数据
axios({
    url: '/api/user/getPartUserInfo',
}).then(res => {
    // 使用reactive绑定响应式的变量需要使用Object.assign进行赋值
    Object.assign(userMessage, res.data.data)
})
</script>

<style scoped>
/* 食谱网站色调样式 */
.box {
  position: relative;
  width: 80%;
  height: 670px;
  margin: 20px auto;
  margin-top: 5vh;
  border-radius: 15px;
  background: linear-gradient(135deg, #FFFFFF 0%, #FDF8F2 100%);
  box-shadow: 0 8px 32px rgba(139, 69, 19, 0.1);
  border: 1px solid #E8D5B7;
}

.header {
  display: table-cell;
  width: 100vw;
  padding-left: 20px;
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
  height: 50px;
  background: linear-gradient(135deg, #FF9800 0%, #FFB74D 100%);
  vertical-align: middle;
  box-shadow: 0 2px 8px rgba(255, 152, 0, 0.2);
}

.name {
  line-height: 50px;
  font-weight: 600;
  float: left;
  letter-spacing: 1px;
  margin-left: 20px;
  font-size: 18px;
  color: #FFFFFF;
  text-shadow: 0 2px 4px rgba(139, 69, 19, 0.3);
}
.button{
  margin-right: 10px;
  float: right;
  line-height: 50px;
}
.deleteBut{
  padding-left: 5px;
  padding-right: 5px;
  background: linear-gradient(135deg, #FF5722 0%, #FF8A65 100%);
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(255, 87, 34, 0.3);
}
.deleteBut:hover {
  background: linear-gradient(135deg, #E64A19 0%, #FF7043 100%);
  transform: translateY(-2px);
}
.header img {
  float: right;
  width: 35px;
  height: 35px;
  border-radius: 35px;
  margin-top: 10px;
  margin-right: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  border: 2px solid #FFFFFF;
}

.chatarea {
  position: absolute;
  top: 50px;
  height: 510px;
  width: 100%;
  background: linear-gradient(135deg, #FFF9F0 0%, #F5E6D3 100%);
  overflow: auto;
  border-left: 1px solid #E8D5B7;
  border-right: 1px solid #E8D5B7;
}

.enter {
  position: absolute;
  background: linear-gradient(135deg, #FF9800 0%, #FFB74D 100%);
  height: 160px;
  width: 100%;
  border-bottom-left-radius: 15px;
  border-bottom-right-radius: 15px;
  bottom: -40px;
  box-shadow: 0 -2px 8px rgba(255, 152, 0, 0.2);
}

.enter img {
  float: left;
  width: 35px;
  height: 35px;
  border-radius: 35px;
  margin-top: 7px;
  margin-left: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  border: 2px solid #FFFFFF;
}

.enterarea {
  resize: none;
  margin-left: 30px;
  margin-top: 10px;
  width:950px;
  height: 100px;
  border-radius: 12px;
  border: 2px solid #FFB74D;
  box-shadow: 0 2px 12px rgba(255, 183, 77, 0.2);
  text-indent: 5px;
  outline: none;
  background: #FFFFFF;
  font-family: inherit;
  padding: 12px;
  transition: all 0.3s ease;
}

.enterarea:focus {
  border-color: #FF9800;
  box-shadow: 0 4px 16px rgba(255, 152, 0, 0.3);
}

.enterbtn {
  float: right;
  width: 80px;
  height: 40px;
  margin-right: 20px;
  margin-top: 10px;
  border-radius: 12px;
  border: none;
  background: linear-gradient(135deg, #FF5722 0%, #FF8A65 100%);
  color: white;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(255, 87, 34, 0.3);
  transition: all 0.3s ease;
}

.enterbtn:hover {
  background: linear-gradient(135deg, #E64A19 0%, #FF7043 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(255, 87, 34, 0.4);
}

.talk_list li {
  margin-top: 20px;
  margin-bottom: 20px;
  overflow: hidden;
}

.left_word img {
  float: left;
  width: 35px;
  height: 35px;
  border-radius: 35px;
  margin-top: 7px;
  margin-left: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  border: 2px solid #FFB74D;
}

.left_word span {
  float: left;
  border: 2px solid #FFB74D;
  border-radius: 18px;
  margin-left: 10px;
  padding: 12px 18px;
  max-width: 290px;
  font-size: 16px;
  line-height: 24px;
  background: linear-gradient(135deg, #FFFFFF 0%, #FFF3E0 100%);
  box-shadow: 0 2px 8px rgba(255, 183, 77, 0.2);
  color: #5D4037;
}
.delBox{
  float: right;
}
.right_word img {
  float: right;
  width: 35px;
  height: 35px;
  border-radius: 35px;
  margin-top: 7px;
  margin-right: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  border: 2px solid #4CAF50;
}

.right_word span {
  float: right;
  border: 2px solid #4CAF50;
  border-radius: 18px;
  margin-right: 10px;
  padding: 12px 18px;
  max-width: 290px;
  font-size: 16px;
  line-height: 24px;
  background: linear-gradient(135deg, #E8F5E8 0%, #F1F8E9 100%);
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.2);
  color: #2E7D32;
}


* {
  margin: 0;
  padding: 0;
}

.clearfix:before,
.clearfix:after {
  content: "";
  display: table;
}

.clearfix:after {
  clear: both;
}


ul {
  margin: 0;
  padding: 0;
}

ul li {
  list-style: none;
}

.enterarea::-webkit-scrollbar {
	 width: 6px;
	 height: 6px;
}
.enterarea::-webkit-scrollbar-thumb {
	border-radius: 3px;
  	-moz-border-radius: 3px;
  	-webkit-border-radius: 3px;
  	background: linear-gradient(135deg, #FF9800 0%, #FFB74D 100%);
}
.enterarea::-webkit-scrollbar-track {
	background-color: transparent;
}

/* 聊天区域滚动条样式 */
.chatarea::-webkit-scrollbar {
  width: 8px;
}
.chatarea::-webkit-scrollbar-thumb {
  border-radius: 4px;
  background: linear-gradient(135deg, #FF9800 0%, #FFB74D 100%);
}
.chatarea::-webkit-scrollbar-track {
  background-color: #F5E6D3;
  border-radius: 4px;
}
</style>
